package org.sluggard.tangela.tencent;

import java.awt.Frame;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.JCheckBox;
import javax.swing.JOptionPane;

import org.sluggard.tangela.core.Container;


public class TencentCheckBox extends JCheckBox{
	
	private TencentToken token;
	
	private String requestToken;

	public TencentCheckBox() {
		super();
		setText("腾讯微博");
		addItemListener(new TencentListener());
		token = TencentToken.getInstence();
		setSelected(token.isState());
	}
	
	private class TencentListener implements ItemListener {

		@Override
		public void itemStateChanged(ItemEvent e) {
			token.setState(e.getStateChange() == ItemEvent.SELECTED);
			if(e.getStateChange() == ItemEvent.DESELECTED) {
				
			} else {
				if(requestToken == null || "".equals(requestToken.trim())) {
					requestToken = OAuth.getRequestToken();
					if(!OAuth.parseToken(requestToken)) {
						
						return;
					}
				}
				if(token.getAccessKey() == null || token.getAccessSecrect() == null) {
					new Thread(new Runnable() {
						
						@Override
						public void run() {
							int n = JOptionPane.showConfirmDialog(new Frame(), "本地没有您的腾讯授权,点击是将跳转到腾讯网站进行授权,请将授权后的授权码输入提示框", "请确认", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
							if(n == JOptionPane.YES_OPTION) {
								OAuth.askPin();
								String s = (String)JOptionPane.showInputDialog(
										new Frame(),
			                            "请输入授权码:",
			                            "Customized Dialog",
			                            JOptionPane.PLAIN_MESSAGE,
			                            null,
			                            null,
			                            "");
								requestToken = OAuth.getAccessToken(s.trim());
								if(!OAuth.parseToken(requestToken,token)) {
									
									return;
								}
								OAuth.setState(2);
								token.setState(true);
							} else {
								setSelected(false);
							}
						}
					}).start();
				}
			}
			Container.addToken(token);
		}
		
	}

}
